#include "commu.h"
#include "commu_route.h"
#include "bsp_uart.h"
#include <string.h>
#include "esp_log.h"

#include "config.h"
#include "mpc.h"
#include "device_manager.h"

static const char *TAG = "commu_route";

#ifndef USE_SYS_MEM
#include "m_memory.h"
extern uint8_t memory_pool[16 * 1024];
extern MemoryPoolManager pool;
#endif

commu_route_t commu_route_table[] = {
    {CMD_DEVICE_MANAGER, process_device_manager_cmd},
    {CMD_BT, NULL},
    {CMD_BLE, NULL},
    {CMD_WIFI, NULL},
    {CMD_FACTORY, NULL}
};

extern void SendToBt(uint8_t *buf, uint8_t len);

int commu_route(uint8_t *buf, uint8_t len)
{
    int ret = 0;
    uint8_t srcdest = buf[2];
    uint8_t tid = srcdest & 0x0F;

    protocol_packet_t *pkt = NULL;
    packet_parse_result_t result = parse_protocol_packet(buf, len, &pkt);

    if (result != PACKET_OK) {
        ESP_LOGI(TAG, "Packet error");
        return 1;
    }

    if (pkt == NULL) {
        ESP_LOGE(TAG, "Packet is NULL");
        return 1;
    }
    switch (tid) {
        case ROUTE_SPI:
            break;
        case ROUTE_UART:
            SendDataToUart(pkt, get_protocol_packet_size(pkt));
            break;
        case ROUTE_SDIO:
            break;
        case ROUTE_BT:
            SendToBt(pkt, get_protocol_packet_size(pkt));
            break;
        case ROUTE_BLE:
            break;
        default:
            for (uint8_t i = 0; i < CMD_MAX; i++) {
                if (commu_route_table[i].cmd == pkt->cmd) {
                    if (commu_route_table[i].process_fun != NULL) {
                        commu_route_table[i].process_fun(pkt);
                    }
                }
            }
            break;
    }
#ifdef USE_SYS_MEM
    free(pkt);
#else
    mempool_free(&pool, pkt);
#endif
    return ret;
}